﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DotSpider.Controls;
using System.Threading;

namespace DotSpider
{
    public partial class Form1 : Form
    {
        public Form1()
        {

            InitializeComponent();
        }

        private MySQL db = new MySQL();
        List<string[]> Queue = new List<string[]>();
        
        private void Form1_Load(object sender, EventArgs e)
        {
            db.Connect();
            db.LoadAllCachedWords();
        }

        private void bStartChecker_Click(object sender, EventArgs e)
        {
            Run();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            CheckQueue();
        }

        private void queueChecker_Tick(object sender, EventArgs e)
        {
            Run();
        }

        private void Run()
        {
            if (bw != null && bw.IsBusy) bw.CancelAsync();

            bw = new BackgroundWorker();
            bw.WorkerSupportsCancellation = true;
            bw.DoWork += bw_DoWork;
            bw.RunWorkerCompleted += bw_Complite;
            Settings.Logger.AddLog("Start");
            bw.RunWorkerAsync("Start");
        }

        private void bw_Complite(object sender, RunWorkerCompletedEventArgs e)
        {
            Settings.Logger.AddLog("Done");
        }

        private BackgroundWorker bw;
        private void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            while(true)
            {
                // Run indexer here for all links
                CheckQueue(true);
                Settings.UpdateQueueList = true;

                int urlCount = Queue.Count;
                if (urlCount < 1) return;

                Settings.Progress = 0;
                for (int i = 0; i < urlCount; i++)
                {
                    if (Queue.Count < 1) break;

                    string url = Queue[0][1];
                    Settings.Logger.AddLog("Indexer > Running page '" + url + "'");
                    Indexer.IndexPage(url, "refresh", db);
                    if (!(Queue.Count < 1)) Queue.RemoveAt(0);
                    Settings.Progress = 100 - ((float)Queue.Count / (float)urlCount) * 100;
                }
            }
        }

        private void CheckQueue()
        {
            CheckQueue(false);
        }

        private void CheckQueue(bool force)
        {
            if (!force 
                && bw != null && bw.IsBusy) return;

            List<string[]> queue = db.FetchQueue();
            if (!force)
            {
                lbQueue.Items.Clear();
                foreach (string[] s in queue)
                {
                    lbQueue.Items.Add(s[1]);
                }
            }
            Queue = queue;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            progressBar1.Value = (int)Math.Round(Settings.Progress);
            List<string> log = new List<string>(Settings.Logger.GetLog());
            Settings.Logger.Clear();
            foreach (string s in log)
            {
                lbLogger.Items.Insert(0, s);
            }

            if (Settings.UpdateQueueList)
            {
                Settings.UpdateQueueList = false;
                lbQueue.Items.Clear();
                foreach (string[] s in (new List<string[]>(Queue)))
                {
                    lbQueue.Items.Add(s[1]);
                }
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            textBox1.Enabled = !textBox1.Enabled;
            button1.Enabled = !button1.Enabled;
        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            try
            {
                Uri url = new Uri(textBox1.Text);
                db.AddToQueue(new List<string>(new string[] { textBox1.Text }));
                textBox1.Clear();
                CheckQueue();
            }
            catch (Exception ex)
            {
                textBox1.Clear();
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            DialogResult res =
                MessageBox.Show("Clear queue?", "Clear", MessageBoxButtons.YesNo, MessageBoxIcon.Question,
                                MessageBoxDefaultButton.Button2);
            if (res == DialogResult.Yes)
            {
                db.RemoveAllQueue();
            }
            CheckQueue();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Coded by Alexey Tishin\nalex@neravaren.com\n2008 year", "About");
        }

        private void bStop_Click(object sender, EventArgs e)
        {
            if (bw != null && bw.IsBusy)
            {
                bw.CancelAsync();
                Settings.Progress = 0;
            }
        }
    }
}
